package com.zyf.project.binaryproto.encoder.impl.fixed;

import com.zyf.project.binaryproto.converter.FixedValueConverter;
import com.zyf.project.binaryproto.encoder.impl.FixedArrayFieldEncoder;
import com.zyf.project.binaryproto.specification.BinarySliceSpecification;
import com.zyf.project.binaryproto.specification.FieldSpecification;
import utils.binary.io.BytesOutputBuffer;
import utils.io.NumberMask;

import java.lang.reflect.Method;

/**
 * <h1>静态对象数组编码器</h1>
 * <p>继承了 {@link FixedArrayFieldEncoder}</p>
 *
 * @author Zhou Yifan
 */
public class FixedObjectArrayFieldEncoder extends FixedArrayFieldEncoder {

    private static final Object[] EMPTY_ARRAY = {};

    public FixedObjectArrayFieldEncoder(
            BinarySliceSpecification binarySliceSpecification,
            FieldSpecification fieldSpecification,
            Method reader,
            FixedValueConverter valueConverter) {
        super(binarySliceSpecification, fieldSpecification, reader, valueConverter);
    }

    /**
     * 对数组类型的值进行固定长度的编码；
     *
     * @param values 待编码对象
     * @param buffer 目标缓冲区
     * @return 写入的字节数
     */
    protected int encodeArray(Object values, BytesOutputBuffer buffer) {
        Object[] valueArray = values == null ? EMPTY_ARRAY : (Object[]) values;

        int count = valueArray.length;

        int counterSize = NumberMask.NORMAL.getMaskLength(count);
        int elementSize = sliceSpecification.getLength();

        int size = counterSize + elementSize * count;
        byte[] outBuff = new byte[size];
        NumberMask.NORMAL.writeMask(count, outBuff, 0);

        for (int i = 0; i < count; i++) {
            valueConverter.encode(valueArray[i], outBuff, counterSize + elementSize * i);
        }

        buffer.write(outBuff);
        return size;
    }

}
